package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsInspectionMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.model.FarmRecordsInspection;
import com.dongjiantong.farmrecords.service.FarmRecordsInspectionService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 防疫中心-检验检测记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsInspectionServiceImpl extends ServiceMybatis<FarmRecordsInspection> implements FarmRecordsInspectionService {

    @Resource
    private FarmRecordsInspectionMapper farmRecordsInspectionMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Override
    public PageInfo<FarmRecordsInspection> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsInspectionMapper == null){
                throw new OPServerException("farmRecordsInspectionMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsInspection> farmRecordsInspectionList = farmRecordsInspectionMapper.selectByMap(map);

            if (farmRecordsInspectionList.size() > 0){
                this.setPicOrVideoList(farmRecordsInspectionList);
            }

            return new PageInfo<FarmRecordsInspection>(farmRecordsInspectionList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 设置关联信息(视频,图片)
     * @param farmRecordsInspectionList
     */
    public void setPicOrVideoList(List<FarmRecordsInspection> farmRecordsInspectionList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }
        List<Long> ids = farmRecordsInspectionList.stream().map(farmRecordsInspection -> farmRecordsInspection.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.INSPECTION.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsInspection farmRecordsInspection : farmRecordsInspectionList){
                List<String> picList = Lists.newArrayList();
                List<String> videoList = Lists.newArrayList();
                for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
                    if ((farmRecordsInspection.getId()).equals(farmRecordsFile.getRelevance_id())){
                        //获取图片
                        if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                            picList.add(farmRecordsFile.getAddress());
                        }
                        //获取视频
                        if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                            videoList.add(farmRecordsFile.getAddress());
                        }
                    }
                }
                //设置图片
                if (picList.size() > 0){
                    farmRecordsInspection.setPicList(picList);
                }
                //设置视频
                if (videoList.size() > 0){
                    farmRecordsInspection.setVideoList(videoList);
                }
            }
        }
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsInspection
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsInspection farmRecordsInspection, Integer toStatus) {
        int id = 0;
        try {
            if (farmRecordsInspectionMapper == null){
                throw new OPServerException("farmRecordsInspectionMapper 为null,请检查");
            }
            Integer fromStatus = farmRecordsInspection.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "FJY";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsInspectionMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsInspection.setNumber(number);

            farmRecordsInspection.setProvince_id(loginInfo.getProvinceId());
            farmRecordsInspection.setCity_id(loginInfo.getCityId());
            farmRecordsInspection.setRegion_id(loginInfo.getRegionId());
            farmRecordsInspection.setStreet_id(loginInfo.getStreetId());
            farmRecordsInspection.setVillage_id(loginInfo.getVillageId());

            farmRecordsInspection.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            if (fromStatus == 0 && toStatus == null) {
                //直接暂存
                farmRecordsInspectionMapper.createOne(farmRecordsInspection);

            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
                //直接提交
                farmRecordsInspection.setStatus(toStatus);
                farmRecordsInspectionMapper.createOne(farmRecordsInspection);
            }

            return farmRecordsInspection.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL,HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsInspection
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsInspection farmRecordsInspection,Integer toStatus) {
        try {
            if (farmRecordsInspectionMapper == null){
                throw new OPServerException("farmRecordsInspectionMapper 为null,请检查");
            }
            farmRecordsInspection.setStatus(toStatus);
            farmRecordsInspection.setUpdated_at(new Date());
            Integer con = farmRecordsInspectionMapper.updateByPrimaryKeySelective(farmRecordsInspection);
            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    @Override
    public PageInfo<FarmRecordsInspection> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsInspection> farmRecordsInspectionList = farmRecordsInspectionMapper.selectListByStatus(map);

        return new PageInfo<FarmRecordsInspection>(farmRecordsInspectionList);
    }
}
